<template>
  <!-- 个人信息框 -->
  <n-flex
    vertical
    justify="center"
    align="center"
    :size="26"
    class="size-fit box-border rounded-8px relative min-h-[300px] min-w-12.5rem select-none cursor-default">
    <!-- 背景 -->
    <img
      class="absolute rounded-t-8px z-2 top-0 left-0 w-full h-100px object-cover"
      src="@/assets/img/dispersion-bg.png"
      alt="" />
    <div class="h-20px"></div>
    <n-flex vertical justify="center" :size="20" class="size-full p-10px box-border z-10 relative">
      <n-flex vertical :size="20">
        <div class="avatar-wrapper relative mx-auto">
          <div class="hover-area absolute top-8px left-8px w-80px h-80px rounded-full z-20">
            <div class="avatar-hover absolute inset-0 rounded-full"></div>
          </div>
          <n-avatar
            class="border-(8px solid [--avatar-border-color])"
            :bordered="true"
            round
            :size="80"
            :src="currentUserProfile.avatar || 'logo.png'"
            fallback-src="/logo.png" />
        </div>

        <!-- 在线状态点 -->
        <template v-if="!statusIcon">
          <n-popover trigger="hover" placement="top" :show-arrow="false">
            <template #trigger>
              <div
                class="z-30 absolute top-72px left-110px cursor-pointer border-(6px solid [--avatar-border-color]) rounded-full size-18px"
                :class="[isOnline ? 'bg-#1ab292' : 'bg-#909090']"></div>
            </template>
            <span>{{ currentStateTitle }}</span>
          </n-popover>
        </template>

        <!-- 独立的状态图标 -->
        <template v-if="statusIcon">
          <n-popover trigger="hover" placement="top" :show-arrow="false">
            <template #trigger>
              <div class="z-30 absolute top-72px left-72px size-26px bg-[--avatar-border-color] rounded-full">
                <img
                  :src="statusIcon"
                  @click="openContent('在线状态', 'onlineStatus', 320, 480)"
                  class="p-4px cursor-pointer rounded-full size-18px"
                  alt="" />
              </div>
            </template>
            <span>{{ currentStateTitle }}</span>
          </n-popover>
        </template>

        <n-flex align="center" :size="8">
          <p
            class="text-underline text-(18px [--chat-text-color]) w-fit mx-auto"
            style="
              font-weight: bold !important;
              font-family:
                system-ui,
                -apple-system,
                sans-serif;
            ">
            {{ currentUserProfile.nick }}
          </p>

          <!--          <n-popover trigger="hover" placement="top" :show-arrow="false">-->
          <!--            <template #trigger>-->
          <!--              <svg class="size-18px cursor-pointer text-[&#45;&#45;chat-text-color]"><use href="#edit"></use></svg>-->
          <!--            </template>-->
          <!--            <span>添加备注</span>-->
          <!--          </n-popover>-->
        </n-flex>

        <!-- 账号 -->
        <!--        <n-flex align="center" :size="10">-->
        <!--          <n-flex align="center" :size="12">-->
        <!--            <p class="text-[&#45;&#45;info-text-color]">群昵称</p>-->
        <!--            <span class="text-(12px [&#45;&#45;chat-text-color])">{{ currentGroupMemberProfile.nameCard || '' }}</span>-->
        <!--          </n-flex>-->
        <!--          <n-tooltip trigger="hover">-->
        <!--            <template #trigger>-->
        <!--              <svg class="size-12px cursor-pointer hover:color-#909090 hover:transition-colors" @click="handleCopy">-->
        <!--                <use href="#copy"></use>-->
        <!--              </svg>-->
        <!--            </template>-->
        <!--            <span>复制账号</span>-->
        <!--          </n-tooltip>-->
        <!--        </n-flex>-->
      </n-flex>

      <!-- 地址 -->
      <n-flex align="center" :size="26" class="select-none">
        <span class="text-[--info-text-color]">公司</span>
        <span class="text-(13px [--chat-text-color])">{{ getCompany() || '未知' }}</span>
      </n-flex>
      <n-flex align="center" :size="26" class="select-none">
        <span class="text-[--info-text-color]">部门</span>
        <span class="text-(13px [--chat-text-color])">{{ getDepartment() || '未知' }}</span>
      </n-flex>

      <n-flex justify="center" align="center" :size="40">
        <n-button v-if="isCurrentUserUid" secondary type="info" @click="openEditInfo"> 编辑资料 </n-button>
        <n-button v-else secondary type="primary" size="small" @click="handleOpenMsgSession"> 发信息 </n-button>
      </n-flex>
    </n-flex>
  </n-flex>
</template>

<script setup lang="ts">
import { MittEnum } from '@/enums/index.ts'
import { useCommon } from '@/hooks/useCommon.ts'
import { leftHook } from '@/layout/left/hook'
import { useMitt } from '@/hooks/useMitt'
import { useTencentUserStore } from '@/stores/tencentUserStore.ts'
import TencentCloudChat, { GroupMember, Profile } from '@tencentcloud/chat'
import { useTencentGroupStore } from '@/stores/tencentGroupStore.ts'
import { useTencentConversationStore } from '@/stores/tencentConversationStore.ts'

const { uid } = defineProps<{
  uid: string
}>()
const tencentConversationStore = useTencentConversationStore()
const tencentUserStore = useTencentUserStore()
const tencentGroupStore = useTencentGroupStore()
const { openMsgSession } = useCommon()
const { openContent } = leftHook()
const currentUserProfile = ref<Partial<Profile>>({})
const currentGroupMemberProfile = ref<Partial<GroupMember>>({})
/** 是否是当前登录的用户 */
const isCurrentUserUid = computed(() => tencentUserStore.myProfile.userID === uid)
/** 是否是我的好友 */
const isOnline = ref<boolean>(true)

// 计算当前用户状态图标
const statusIcon = computed(() => {
  return null
})

// 计算当前状态的标题
const currentStateTitle = ref('在线')

const openEditInfo = () => {
  useMitt.emit(MittEnum.OPEN_EDIT_INFO)
}

// 处理复制账号
// const handleCopy = () => {
//   const account = currentUserProfile.value.nick
//   if (account) {
//     navigator.clipboard.writeText(account)
//     window.$message.success(`复制成功 ${account}`)
//   }
// }

let enableScroll = () => {}

const handleOpenMsgSession = async () => {
  enableScroll() // 在打开新会话前恢复所有滚动
  await openMsgSession(currentUserProfile.value, 'user')
}

watchEffect(async () => {
  if (tencentUserStore.userProfileMap[uid] === undefined) {
    await tencentUserStore.getUserProfile({ userIDList: [uid] })
  }
  currentUserProfile.value = tencentUserStore.userProfileMap[uid]
  if (tencentConversationStore.isGROUP) {
    const groupID = tencentConversationStore.currentConv?.groupProfile?.groupID

    const mf = tencentGroupStore.groupMemberProfileMap[groupID!]
    if (groupID && (mf === undefined || mf[uid] === undefined)) {
      await tencentGroupStore.getGroupMemberProfile({ groupID: groupID, userIDList: [uid] })
    }
    currentGroupMemberProfile.value = tencentGroupStore.groupMemberProfileMap[groupID!][uid]
  }

  if (!isCurrentUserUid.value) {
    try {
      if (!tencentUserStore.userStatusMap[uid]) {
        await tencentUserStore.getUserStatus({ userIDList: [uid] })
      }
      const userStatus = tencentUserStore.userStatusMap[uid]
      if (userStatus) {
        const { statusType } = userStatus
        if (statusType === TencentCloudChat.TYPES.USER_STATUS_ONLINE) {
          isOnline.value = true
          currentStateTitle.value = '在线'
        } else if (statusType === TencentCloudChat.TYPES.USER_STATUS_OFFLINE) {
          isOnline.value = false
          currentStateTitle.value = '离线'
        } else if (statusType === TencentCloudChat.TYPES.USER_STATUS_UNLOGINED) {
          isOnline.value = false
          currentStateTitle.value = '未登录'
        } else {
          isOnline.value = false
          currentStateTitle.value = '未知'
        }
      }
    } catch (e) {
      console.log('get user status exception', e)
    }
  }
})

const getCompany = () => {
  return currentUserProfile.value?.profileCustomField?.find((i: any) => i.key === 'Tag_Profile_Custom_CShName').value
}

const getDepartment = () => {
  return currentUserProfile.value?.profileCustomField?.find((i: any) => i.key === 'Tag_Profile_Custom_DepName').value
}

onMounted(() => {
  // 注入 enableAllScroll 方法
  const popoverControls = inject('popoverControls', { enableScroll: () => {} })
  enableScroll = () => {
    if (typeof popoverControls.enableScroll === 'function') {
      popoverControls.enableScroll()
    }
  }
})
</script>

<style scoped lang="scss">
.avatar-wrapper {
  .hover-area {
    .avatar-hover {
      opacity: 0;
      transition: opacity 0.4s ease-in-out;
      background: rgba(0, 0, 0, 0.2);
      cursor: pointer;
    }
  }

  .hover-area:hover .avatar-hover {
    opacity: 1;
  }
}

.text-underline {
  &:hover {
    @apply cursor-pointer underline underline-offset-3 decoration-2 decoration-[#606060];
  }
}
</style>
